﻿using FluentFTP;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.WriteLine("123".Substring("123".IndexOf('3')));
            //GetDirctory("ftp://user1:123123@127.0.0.1", "/project1").ForEach(Console.WriteLine);


            //FtpClient client = new FtpClient("127.0.0.1", new NetworkCredential("user1", "123123"));
            //client.GetListing("/project1").ToList().ForEach(r => Console.WriteLine(r.FullName));
            //client.CreateDirectory("/k1/k2/k3");

            myFtp ftp = new myFtp("ftp://user1:123123@127.0.0.1");

            //ftp.UploadDir("d:\\mytable", "/k1/k2/k3");
            ftp.UploadFile("d:\\mytable\\index.html", "/index.html");
        }

        /// <summary>
        /// 从ftp服务器上获得文件夹列表
        /// </summary>
        /// <param name="RequedstPath">服务器下的相对路径</param>
        /// <returns></returns>
        public static List<string> GetDirctory(string ftp, string RequedstPath)
        {
            List<string> strs = new List<string>();
            try
            {
                string uri = ftp + RequedstPath;   //目标路径 path为服务器地址
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
                // ftp用户名和密码
                //reqFTP.Credentials = new NetworkCredential(username, password);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名

                string line = reader.ReadLine();
                while (line != null)
                {

                    string msg = line.Substring(line.LastIndexOf("<DIR>") + 5).Trim();
                    strs.Add(msg);

                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return strs;
            }
            catch (Exception ex)
            {
                Console.WriteLine("获取目录出错：" + ex.Message);
            }
            return strs;
        }
    }

    class myFtp : IDisposable
    {
        FtpClient client { get; }
        string basePath { get; set; }
        public myFtp(string ftpUrl)
        {
            if (!ftpUrl.StartsWith("ftp://", StringComparison.OrdinalIgnoreCase))
                throw new Exception("ftpurl不正确");


            var part1 = ftpUrl.Substring("ftp://".Length);

            string part2 = null;
            int index = part1.IndexOf('/');
            if (index == -1)
            {
                part2 = part1;
                basePath = "/";
            }
            else
            {
                part2 = part1.Substring(0, index);
                basePath = part1.Substring(index);
            }

            var arr = part2.Split(new[] { ':', '@' }, StringSplitOptions.RemoveEmptyEntries);
            string user = arr[0];
            string pwd = arr[1];
            string host = arr[2];


            client = new FtpClient(host, new NetworkCredential(user, pwd));
            client.Connect();
        }

        public void UploadFile(string localFile, string remotePath)
        {
            var path = basePath.TrimEnd('/') + '/' + remotePath.TrimStart('/');
            client.UploadFile(localFile, path, FtpExists.Overwrite, true);
        }


        public void UploadDir(string localDir, string remoteDir)
        {
            var path = basePath.TrimEnd('/') + '/' + remoteDir.TrimStart('/');
            client.CreateDirectory(path);


            var files = Directory.EnumerateFiles(localDir, "*.*", SearchOption.AllDirectories);
            var dirs = Directory.EnumerateDirectories(localDir);


            foreach (var item in files)
            {
                UploadFile(item, remoteDir + '/' + Path.GetFileName(item));
            }

            //foreach (var item in dirs)
            //{
            //    UploadDir(item, remoteDir + '/' + Path.GetFileName(item));
            //}
        }


        public void Dispose()
        {
            client?.Dispose();
        }
    }
}
